package cn.xuqiudong.sso.shiro;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

/**
 * REDIS 缓存 shiro session
 *  修改redisTemplate 的 序列化 为  GenericJackson2JsonRedisSerializer
 * @author VIC.xu
 * 备注: 本方法不要打log日志,因为本项目重写了日志布局会获取当前用户信息,从而致使循环调用(此处调用日志布局-->日志布局调用此处session)
 *
 */
public class RedisCache2ERelaySimpleSession<K> implements Cache<K, SimpleSession> {

	private String							cacheName;

	private static final String				DEFAULT_CACHE_NAME	= "shiro-activeSessionCache";

	private HashOperations<String, K, RelaySimpleSession>	hashOperations;

	public RedisCache2ERelaySimpleSession(String cacheName, RedisTemplate<String, SimpleSession> redisTemplate) {
		if (StringUtils.isEmpty(cacheName)) {
			cacheName = DEFAULT_CACHE_NAME;
		}
		if (redisTemplate == null) {
			throw new IllegalArgumentException("redisTemplate can not be null");
		}
		this.hashOperations = redisTemplate.opsForHash();
		this.cacheName = cacheName;
	}

	@Override
	public SimpleSession get(K key) throws CacheException {
		RelaySimpleSession relay = hashOperations.get(cacheName, key);
		if (relay == null){ return null;}

		return relay.toSimpleSession();
	}

	@Override
	public SimpleSession put(K key, SimpleSession value) throws CacheException {
		if (value == null){ return null;}

		RelaySimpleSession relay = new RelaySimpleSession(value);
		RelaySimpleSession oldRelay = hashOperations.get(cacheName, key);
		hashOperations.put(cacheName, key, relay);
		return oldRelay != null ? oldRelay.toSimpleSession() : null;
	}

	@Override
	public SimpleSession remove(K key) throws CacheException {
		RelaySimpleSession oldRelay = hashOperations.get(cacheName, key);
		hashOperations.delete(cacheName, key);
		return oldRelay != null ? oldRelay.toSimpleSession() : null;
	}

	@Override
	public void clear() throws CacheException {
		hashOperations.delete(cacheName);
	}

	@Override
	public int size() {
		Long size = hashOperations.size(cacheName);
		return size != null ? size.intValue() : 0;
	}

	@Override
	public Set<K> keys() {
		return hashOperations.keys(cacheName);
	}

	/**
	 * ICBCSTL-64072  由于Java类serialVersionUID变更造成shiro的session发序列化失败：删除这样的session
	 */
	@Override
	public Collection<SimpleSession> values() {
		try {
			List<RelaySimpleSession> relays = hashOperations.values(cacheName);
			List<SimpleSession> sessions = new ArrayList<>();
			for (RelaySimpleSession r : relays) {
				sessions.add(r.toSimpleSession());
			}
			return sessions;
		} catch (Exception ex) {
			cleanFatalSession();
			return Collections.emptyList();
		}
	}

	/**
	 * 清理掉引起错误的session,当获取全部session发生错误的时候
	 */
	private void cleanFatalSession() {
		Set<K> keys = hashOperations.keys(cacheName);
		if (CollectionUtils.isEmpty(keys)) {
			return;
		}
		for (K k : keys) {
			try {
				hashOperations.get(cacheName, k);
			} catch (Exception e) {
				//发生错误，清理掉此session
				hashOperations.delete(cacheName, k);
			}
		}
	}

}